from nicegui import ui

from ServerSide.Model.UserProfile import UserProfile, UserProfileDal


class LoginLogic:
    dal= UserProfileDal()
    def checkLogin(self,username:str,password:str,ip:str,v,session_info):
        #check username and password in database with peeweemodel
        print(username,password)
        user= self.dal.findByUsername(username)
        if user is None:
            v.set_text("没有此用户")
            return
        if user.password!=password:
            v.set_text("用户名或密码错误")
            return
        if user.ip!=ip:
            v.set_text("IP地址不对")
            return
        session_info['id'] = user.username
        # print("session id:",session_info.session['id'])
        print("session id:",session_info['id'])
        ui.open("/")

    def register(self,username:str,password:str,ip:str):
        u1 = UserProfile(username=username, password=password, ip=ip)
        try:
            u1.save()
        except Exception as e:
            UserProfile.create_table()
            u1.save()
        print("saved")
        from starlette.responses import RedirectResponse
        ui.open("/loginform")

    def checkPassword(self,password:str,password2:str,v):
        if password!=password2:
            v.set_text("两次输入密码不一样")
        else:
            v.set_text("")

